package com.dy.web.controller.applet;

import com.dy.common.core.controller.BaseController;
import com.dy.common.core.domain.AjaxResult;
import com.dy.common.utils.DateUtils;
import com.dy.common.utils.StringUtils;
import com.dy.system.domain.*;
import com.dy.system.domain.vo.*;
import com.dy.system.service.*;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/applet")
public class IndexController extends BaseController {

    @Autowired
    private IAppletBannerService appletBannerService;
    @Autowired
    private IFreshMedicalMachineService freshMedicalMachineService;
    @Autowired
    private IMedicalInstitutionService medicalInstitutionService;
    @Autowired
    private IWarningMessageService warningMessageService;
    @Autowired
    private IMedicalEquipmentReportLogService medicalEquipmentReportLogService;

    @Autowired
    private IFreshWarningMsgTypeDetailService freshWarningMsgTypeDetailService;













    @GetMapping("/banner/list")
    public AjaxResult bannerList(){
        //banner data
        AppletBanner banner = new AppletBanner();
        banner.setStatus("0");
        banner.setIsShow("0");
        List<AppletBanner> bannerList = appletBannerService.selectAppletBannerList(banner);
        String imgUrl = "https://dyep.cc/prod-api";
        bannerList.forEach(m ->{
            m.setNoticeCover(StringUtils.isNoneBlank(m.getNoticeCover()) ? imgUrl + m.getNoticeCover() : "");
        });
        Map<String,Object> rowsMap = new HashMap<>();
        rowsMap.put("bannerList",bannerList);
        return AjaxResult.success(rowsMap);
    }






    /***
     * 大屏接口
     * @param deptId
     * @return
     */
    @GetMapping("/large/screen/data")
    public AjaxResult largeScreenData(Long deptId){

        Map<String,Object> resultMap = new HashMap<>();


        //设备列表
        StatisticsVo statisticsVo = new StatisticsVo();
        List<FreshMedicalMachine> machineList = freshMedicalMachineService.selectFreshMedicalMachineList(new FreshMedicalMachine());
        List<FreshMedicalMachine> offEquipmentList = machineList.stream().filter(m -> "0".equals(m.getNetworkStatus())).collect(Collectors.toList());
        statisticsVo.setOffEquipmentCount(offEquipmentList.size());
        statisticsVo.setOnEquipmentCount(machineList.size() - offEquipmentList.size());

        List<MedicalInstitution> institutions = medicalInstitutionService.selectMedicalInstitutionList(new MedicalInstitution());
        statisticsVo.setMedicalCount(institutions.size());
        //日处理量
        Integer zuotianHandle = medicalEquipmentReportLogService.getMedicalHandleShengData("zuotian",null,null);
        Integer jintianHandle = medicalEquipmentReportLogService.getMedicalHandleShengData("jintian",null,null);
        Integer fresh = jintianHandle >= zuotianHandle ? jintianHandle - zuotianHandle : 0;
        statisticsVo.setDayTotalHandle(String.valueOf(fresh));
        //季处理量
        Integer jiduHandle = medicalEquipmentReportLogService.getMedicalHandleData("jidu",null,null);
        statisticsVo.setQuarterTotalHandle(String.valueOf(jiduHandle));
        //总处理量
        Integer totalHandle = medicalEquipmentReportLogService.getMedicalHandleData(null,null,null);
        statisticsVo.setTotalHandle(String.valueOf(totalHandle));
        resultMap.put("statisticsVo",statisticsVo);
        //机构信息

        //机构列表
        //查询机构信息
        MedicalInstitution institution = new MedicalInstitution();
        institution.setDeptId(deptId);
        institution.setStatus("0");
        List<MedicalInstitution> institutionList = medicalInstitutionService.selectMedicalInstitutionList(institution);
        String img = "https://dyep.cc/prod-api";
        institutionList.forEach(m ->{
            FreshMedicalMachine machine = freshMedicalMachineService.selectFreshMedicalMachineByInstitutionId(m.getId());
            if (machine != null){
                m.setLongitude(machine.getLongitude());
                m.setDimension(machine.getDimension());
            }
            //查询设备数量
            Integer count = freshMedicalMachineService.findMachineCount(m.getId());
            logger.error("insId = {} and 查询设备数量 = {}",m.getId(),count);
            m.setEquipmentCount(count);
            m.setEquipmentCount(count);
            m.setXkImg(StringUtils.isNoneBlank(m.getXkImg()) ? img + m.getXkImg() : "");
            m.setMtImg(StringUtils.isNoneBlank(m.getMtImg()) ? img + m.getMtImg() : "");
        });
        resultMap.put("institutionList",institutionList);
        return AjaxResult.success(resultMap);
    }


    /***
     * 获取大屏医院处理量相关信息
     * @param institutionId
     * @return
     */
    @GetMapping("/get/ins/handle/data")
    public AjaxResult getInstitutionHandleData(@RequestParam Long institutionId){
        MedicalInstitution m = medicalInstitutionService.selectMedicalInstitutionById(institutionId);
        if (m == null){
            return success();
        }
        String img = "https://dyep.cc/prod-api";
        FreshMedicalMachine machine = freshMedicalMachineService.selectFreshMedicalMachineByInstitutionId(m.getId());
        if (machine != null){
            m.setLongitude(machine.getLongitude());
            m.setDimension(machine.getDimension());
            m.setOpCode(StringUtils.isNoneBlank(machine.getOpCode()) ? img + machine.getOpCode() : "");
        }
        //查询设备数量
        Integer count = freshMedicalMachineService.findMachineCount(m.getId());
        logger.error("insId = {} and 查询设备数量 = {}",m.getId(),count);
        m.setEquipmentCount(count);
        m.setXkImg(StringUtils.isNoneBlank(m.getXkImg()) ? img + m.getXkImg() : "");
        m.setMtImg(StringUtils.isNoneBlank(m.getMtImg()) ? img + m.getMtImg() : "");

        //总处理量
        Integer jgzcll = medicalEquipmentReportLogService.getMedicalHandleData(null,m.getId(),null);
        m.setTotalHandle(String.valueOf(jgzcll));
        //日处理量
        Integer jgzt = medicalEquipmentReportLogService.getMedicalHandleShengData("zuotian",m.getId(),null);
        Integer jgjt = medicalEquipmentReportLogService.getMedicalHandleShengData("jintian",m.getId(),null);
        Integer fresh01 = jgjt >= jgzt ? jgjt - jgzt : 0;
        m.setDayHandle(String.valueOf(fresh01));
        //月处理量
        Integer benyue = medicalEquipmentReportLogService.getMedicalHandleData("benyue",m.getId(),null);
        m.setMonthHandle(String.valueOf(benyue));
        return AjaxResult.success(m);
    }

    /***
     * 获取未上传记录的机构列表
     * @param session
     * @return
     */
    @GetMapping("/get/not/upload/inst")
    public AjaxResult getNotUploadedInstitutionList(@RequestParam(required = false) Long deptId,
                                                    @RequestParam(required = false) String year,
                                                    @RequestParam(required = false) String session){
        //查询未上传检测报告的机构
        List<MedicalInstitution> institutionList = medicalInstitutionService.getNotUploadedInstitutionList(deptId,session,year);
        return AjaxResult.success(institutionList);
    }


    /***
     * 告警信息
     * @return
     */
    @GetMapping("/get/warning/msg")
    public AjaxResult getWarningMessageInfo(@RequestParam Integer pageNo,@RequestParam Integer pageSize,Long medicalId){
        PageHelper.startPage(pageNo,pageSize,"id desc");
        List<WarningMessage> messageList = warningMessageService.selectWarningMessageAllList(medicalId);
        FreshWarningMsgTypeDetail message = new FreshWarningMsgTypeDetail();
        message.setMedicalId(medicalId);
        List<FreshWarningMsgTypeDetail> warningMessages = freshWarningMsgTypeDetailService.selectFreshWarningMsgTypeDetailList(message);
        logger.info("warningMessages size ={}",warningMessages.size());
        List<WarningMessageVo> voList = new ArrayList<>();
        warningMessages.forEach(msg -> {
            MedicalInstitution institution = medicalInstitutionService.selectMedicalInstitutionById(msg.getMedicalId());
            if (institution == null){
                return;
            }
            WarningMessageVo vo = new WarningMessageVo();
            vo.setCode(msg.getCode());
            //机构名称
            vo.setMedicalIdName(institution.getName());
            vo.setWarningContent("纯净水位过低");
            vo.setWarningType("clearwaterlow");
            vo.setWarningTime(String.valueOf(msg.getCreateTime().getTime()));
            vo.setStatus(1);
            vo.setRunningStatus(msg.getRunningStatus());
            voList.add(vo);

        });
        return AjaxResult.success(voList);
    }




    /****
     * 获取检测值和日处理量
     * @param institutionId
     * @return
     */
    @GetMapping("/large/screen")
    public AjaxResult largeScreenDataTwo(@RequestParam Long institutionId){
        //查询机构下面的设备

        DetectionValueVo detectionValueVo = new DetectionValueVo();
        List<DayHandleVo> dayHandleVoList = new ArrayList<>();
        dayHandleVoList.add(new DayHandleVo());
        Map<String,Object> resultMap = new HashMap<>();
        //检测值
        resultMap.put("detectionValueVo",detectionValueVo);

        List<String> dayList = DateUtils.get7Day();
        long length = dayList.size() - 1;
        for (int i = 0; i < length; i++){
            DayHandleVo dayHandleVo = new DayHandleVo();
            String time = null;
            String freshTime = null;
            //如果是最后一天，当天
            time = dayList.get(i);
            freshTime = dayList.get(i + 1);
            dayHandleVo.setTime(freshTime);
            Integer count = medicalEquipmentReportLogService.getMedicalHandleDataByInsIdAndTime(institutionId,time);
            Integer countNew = medicalEquipmentReportLogService.getMedicalHandleDataByInsIdAndTime(institutionId,freshTime);
            Integer fresh = countNew >= count ? countNew - count : 0;
            dayHandleVo.setSewaget(String.valueOf(fresh));
            dayHandleVoList.add(dayHandleVo);
        }
        //日处理量数组
        dayHandleVoList.remove(0);
        resultMap.put("dayHandleVoList",dayHandleVoList);
        return AjaxResult.success(resultMap);
    }



}
